package com.wanmait.wanmarecruit.shiro;

import com.auth0.jwt.exceptions.JWTVerificationException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class JWTFilter extends BasicHttpAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }


    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response){
        return true;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        String method = req.getMethod();
        if ("OPTIONS".equals(method))
        {
            return true;
        }
        String token = req.getHeader("token");
        System.out.println(token);
        if (token==null)
        {
            req.setAttribute("exception",new AuthenticationException("token不能为空"));
            try {
                req.getServletContext().getRequestDispatcher("/manage/errorToken").forward(request,response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
        BearerToken bearerToken = new BearerToken(token);
        try {
            this.getSubject(request,response).login(bearerToken);
        } catch (AuthenticationException e) {
            req.setAttribute("exception",new AuthenticationException("token验证失败"));
            try {
                req.getServletContext().getRequestDispatcher("/manage/errorToken").forward(request,response);
            } catch (ServletException servletException) {
                servletException.printStackTrace();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            return false;
        }
        return true;
    }
}
